<template>
  <div class="fields-manage">
    <div class="setting-content">
      <h2 class="setting-header">
        <strong>字段管理</strong>
      </h2>
      <div class="header-option">
        <el-dropdown>
          <el-tag effect="light" size="large" class="el-dropdown-link">
            <p style="display: flex; align-items: center">
              <span style="margin-right: 5px">{{ curModel.name }}模型</span>
              <el-icon><ArrowDownBold /></el-icon>
            </p>
          </el-tag>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-for="(item, index) in modelList" :key="index" @click="changeModel(item)">{{ item.name }}模型</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button v-permission="['build:model:fieldSetting:add']" type="primary" class="add-field" @click="handleAddField">添加表单字段</el-button>
      </div>
      <div class="list-content">
        <RuifoxTable
          border
          :loading="tableLoading"
          v-model:tableData="fieldList"
          v-model:fieldList="headerList"
          :canDrag="hasPermission(['build:model:fieldSetting:edit'])"
          :headerTextAlign="'center'"
          :textAlign="'center'"
          @handleSort="handleSort"
        >
        <template #headerIsSystem>
          <el-popover placement="right" :width="200" trigger="hover" content="创建模型时，系统自动创建的字段">
            <template #reference>
              <el-icon color="#ee9f28">
                <QuestionFilled />
              </el-icon>
            </template>
          </el-popover>
        </template>
        <template #headerSort>
          <el-popover placement="right" :width="200" trigger="hover" content="开启排序后，后台可以根据当前字段进行排序">
            <template #reference>
              <el-icon color="#ee9f28">
                <QuestionFilled />
              </el-icon>
            </template>
          </el-popover>
        </template>
        <template #headerIsShow>
          <el-popover placement="right" :width="200" trigger="hover" content="开启后后台列表中将默认有这个字段显示">
            <template #reference>
              <el-icon color="#ee9f28">
                <QuestionFilled />
              </el-icon>
            </template>
          </el-popover>
        </template>
        <template #headerIsShowControl>
          <el-popover placement="right" :width="200" trigger="hover" content="开启后后台列表显示列配置中才能勾选该字段，否则不显示">
            <template #reference>
              <el-icon color="#ee9f28">
                <QuestionFilled />
              </el-icon>
            </template>
          </el-popover>
        </template>
        <template #isSystem="{ element }">
          <span v-if="element.isSystem" class="yes">√</span>
          <span v-else class="no">×</span>
        </template>
        <template #isOrder="{ element }">
          <el-switch :disabled="!hasPermission(['build:model:fieldSetting:edit'])" v-model="element.isOrder" :before-change="handleUpdateField.bind(this, element, 'isOrder')" :loading="curField.id === element.id && loadingFlag" />
        </template>
        <template #isRequired="{ element }">
          <el-switch :disabled="!hasPermission(['build:model:fieldSetting:edit'])" v-model="element.isRequired" :before-change="handleUpdateField.bind(this, element, 'isRequired')" :loading="curField.id === element.id && loadingFlag" />
        </template>
        <template #isShow="{ element }">
          <el-switch :disabled="!hasPermission(['build:model:fieldSetting:edit'])" v-model="element.isShow" :before-change="handleUpdateField.bind(this, element, 'isShow')" :loading="curField.id === element.id && loadingFlag" />
        </template>
        <template #isShowControl="{ element }">
          <el-switch :disabled="!hasPermission(['build:model:fieldSetting:edit'])" v-model="element.isShowControl" :before-change="handleUpdateField.bind(this, element, 'isShowControl')" :loading="curField.id === element.id && loadingFlag" />
        </template>
        <template #options='{ element }'>
          <div class="table-td-option unmover">
            <el-button v-permission="['build:model:field:delete']" link type="primary" @click="handleDeleteField(element)" :disabled="element.isSystem || element.setting?.isDefault">删除</el-button>
            <el-button v-permission="['build:model:fieldSetting:edit']" link type="primary" @click="handleEditField(element)">编辑</el-button>
            <el-button v-permission="['build:model:fieldSetting:add']" link type="primary" @click="handleCopyField(element)" :disabled="element.isSystem">复制</el-button>
          </div>
        </template>
      </RuifoxTable>
      </div>
    </div>
    <!-- 复制字段 -->
    <el-dialog v-model="copyDialog" :title="'复制字段（' + currentField.name + '）'" width="500px">
      <!-- 填写字段名和字段别名 -->
      <el-form ref="copyFormRef" :model="copyForm" :rules="copyRules" label-width="auto"> 
        <el-form-item label="字段名" prop="field">
          <el-input v-model="copyForm.field" placeholder="使用小写字母命名，多个单词用下划线连接，如create_time" />
        </el-form-item>
        <el-form-item label="字段别名" prop="name">
          <el-input v-model="copyForm.name" placeholder="请输入字段别名，如创建时间" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="copyDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitCopy">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { getModelList, getFieldList, deleteField, updateField, updateSort, insertField } from '@/api/model'
import { QuestionFilled, ArrowDownBold } from '@element-plus/icons-vue'
import { hasPermission } from '@ruifox-cms/utils'

const router = useRouter()
const curModel = ref({})
// 模型类型列表
const modelList = ref([])
const _getModelList = async () => {
  let res = await getModelList()
  if (res.code === 20000) {
    modelList.value = res.data
    const modelId = router.currentRoute.value.query.modelId
    if (modelId) {
      curModel.value = modelList.value.find(item => item.id === Number(modelId))
    } else {
      curModel.value = modelList.value[0]
    }
  }
}
const changeModel = item => {
  curModel.value = item
  _getFieldList()
}
// 列表头部配置
const headerList = reactive([
  {title: '字段名', name: 'field'},
  {title: '别名', name: 'name'},
  {title: '类型', name: 'component'},
  {title: '系统', name: 'isSystem', slotHeader: 'headerIsSystem'},
  {title: '排序', name:'isOrder', slotHeader: 'headerSort'},
  {title: '必填', name:'isRequired'},
  {title: '列表', name:'isShow', slotHeader: 'headerIsShow'},
  {title: '列可选', name:'isShowControl', slotHeader: 'headerIsShowControl'},
  {title: '操作', name:'options'}
])
// 获取字段
const tableLoading = ref(false)
const fieldList = ref([])
const _getFieldList = async () => {
  tableLoading.value = true
  let res = await getFieldList({ modelId: curModel.value.id })
  if (res.code === 20000) {
    fieldList.value = res.data
  }
  tableLoading.value = false
}
const handleAddField = () => {
  router.push({ path: '/resource/model/fieldSetting', query: { modelName: curModel.value.name, modelId: curModel.value.id } })
}
const handleEditField = data => {
  router.push({ path: '/resource/model/fieldSetting', query: { fieldId: data.id, modelName: curModel.value.name, modelId: curModel.value.id } })
}
// 复制字段
const copyDialog = ref(false)
const copyForm = ref({})
const copyFormRef = ref(null)
const currentField = ref({})
const copyRules = ref({
  field: [{ required: true, message: '请输入字段名', trigger: 'blur' }],
  name: [{ required: true, message: '请输入字段别名', trigger: 'blur' }]
})
const handleCopyField = data => {
  copyDialog.value = true
  Object.assign(copyForm.value, data)
  currentField.value = data
  copyForm.value.field = ''
  copyForm.value.name = ''
  delete copyForm.value.id
  delete copyForm.value['default-index']
  delete copyForm.value.sort
}
const handleSubmitCopy = () => {
  copyFormRef.value.validate(valid => {
    if (valid) {
      insertField(copyForm.value).then(res => {
        if (res.code === 20000) {
          ElMessage.success('复制成功')
          copyDialog.value = false
          _getFieldList()
        }
      })
    }
  })
}
const handleDeleteField = data => {
  ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">是否删除所选字段？</p><span style="font-size: 14px;color: #FF5240;">删除后字段将被移除</span></div>', '删除确认', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(() => {
    deleteField({ id: data.id }).then(() => {
      //更新节点
      _getFieldList()
      ElMessage({
        showClose: true,
        message: '删除成功',
        type: 'success'
      })
    })
  })
}
// 字段更新
const loadingFlag = ref(false)
const curField = ref({})
const handleUpdateField = async (row, key) => {
  curField.value = row
  loadingFlag.value = true
  const data = {
    id: row.id,
    [key]: !row[key]
  }
  return new Promise((resolve, reject) => {
    updateField(data)
      .then(res => {
        loadingFlag.value = false
        if (res.code === 20000) {
          ElMessage({
            showClose: true,
            message: '修改成功',
            type: 'success'
          })
          return resolve(true)
        }
      })
      .catch(() => {
        loadingFlag.value = false
        return reject(new Error('Error'))
      })
  })
}
// 拖拽排序
const handleSort = async () => {
  const sort = fieldList.value.map((item, index) => {
    return {
      id: item.id,
      sort: fieldList.value.length - index
    }
  })
  await updateSort(sort)
}

onMounted(async () => {
  await _getModelList()
  if (curModel.value.id) {
    await _getFieldList()
  }
})
</script>

<style scoped lang="scss">
.fields-manage {
  .list-content {
    margin-top: 15px;
    .el-switch{
      height: initial;
    }
    span {
      &.yes {
        color: green;
      }
      &.no {
        color: red;
      }
    }
  }
}
::v-deep .el-dropdown {
  margin-right: 10px;
  cursor: pointer;
}
</style>
